# !/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from mytest.utils.forms import BugModelForm
from mytest import models
from django.views.decorators.csrf import csrf_exempt
from mytest.utils.pagination import Pagination


@csrf_exempt
def bug_page(request):
    """ 缺陷列表 """

    # 1. 查询关键字处理
    search = {}

    keyword = request.GET.get('keyword', "")

    if keyword:
        search = {
            "username__contains": keyword
        }

    queryset = models.Bug.objects.all().order_by('-id').filter(**search)

    # 分页的请求参数
    parameter = {
        "request": request,
        "queryset": queryset,
        "page_size": 10
    }

    # data['keyword'] = keyword  # 临时加个搜索关键字看效果
    data = Pagination(**parameter).get_content()
    form = BugModelForm()
    data['form'] = form

    response = {
        "code": 200,
        "msg": "操作成功",
        "data": data
    }

    return render(request, "mytest/data_bug_list.html", response)


@csrf_exempt
def add_bug(request):
    """ 缺陷添加 """

    form = BugModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        result = {
            "status": True,
        }
        return JsonResponse(result)

    # print("错误返回")
    return JsonResponse({"status": False, "error": form.errors})


def delete_bug(request, nid):
    """ 删除缺陷 """
    Bug.objects.filter(id=nid).delete()

    return redirect("mytest:bug_list")


@csrf_exempt
def bug_edit(request):
    """ 编辑缺陷 """
    uid = request.GET.get("uid")
    # print(uid)
    row_object = Bug.objects.filter(id=uid).first()  # 对象不能以json形式进行传送。
    row_dict = Bug.objects.filter(id=uid).values().first()
    # print(row_dict)

    if not row_object:
        return JsonResponse({"status": False, "tips": "Bug编辑失败，数据ID不存在。"})

    if request.method == "GET":
        result = {
            "status": True,
            "data": {
                "rows": row_dict
            }
        }
        return JsonResponse(result)

    # post负责提交时的修改以及报错提示。
    form = BugModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})

    return JsonResponse({"status": False, "error": form.errors})
